package top.eggcode.setup.config.shiro;

import lombok.RequiredArgsConstructor;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.credential.SimpleCredentialsMatcher;
import org.springframework.stereotype.Component;
import top.eggcode.system.modules.user.model.AccountEntity;
import top.eggcode.system.modules.user.store.AccountRepository;
import top.eggcode.system.modules.user.tool.KeyTool;

import java.util.List;

/**
 * 登录密码匹配规则
 */
@RequiredArgsConstructor
@Component
public class LoginCredentialsMatcher extends SimpleCredentialsMatcher {

    private final AccountRepository accountRepository;

    @Override
    public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {

        // 委托人
        String username = (String) token.getPrincipal();

        // 凭据
        String password = String.valueOf((char[]) token.getCredentials());

        List<AccountEntity> accountList = accountRepository.findByUsername(username);
        AccountEntity account = accountList.get(0);
        String ciphertext = KeyTool.encryptUserPassword(password, account.getSalt());
        // 比较密文
        return account.getPassword().equals(ciphertext);
    }
}
